package com.wgj.android.ui.activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.ListHttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.jiaai.xui.view.widget.XTopbarView;
import com.jiaai.xui.view.widget.loadingview.XLoadingView;
import com.wgj.android.R;
import com.wgj.android.adapter.GroupAdapter;
import com.wgj.android.dialog.ModifyGroupDialog;
import com.wgj.android.entity.Group;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.http.WeiXinEvents;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.event.ContactEvent;
import com.wgj.android.http.weixin.model.WXInfo;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.zfp.GetWXFriendService;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
/**
 * ========================================
 * 作    者： 佳爱网络有限公司(wwww.jiaailove.com)
 * 版    本： 1.0
 * 创建日期：  2017/12/6
 * 描    述： 微信好友分级
 * 修订历吏：
 * =========================================
 */

public class WXGroupActivity  extends AppCompatActivity {
    private WXInfo wxInfo;

    @BindView(R.id.groupListView)
    SwipeMenuRecyclerView groupListView;
    @BindView(R.id.topbarView)
    XTopbarView  topbarView;


    @BindView(R.id.loadingView)
    XLoadingView loadingView;



    private List<Group> groups=new ArrayList<>();
    private GroupAdapter groupAdapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.group_activity);
        ButterKnife.bind(this);
        wxInfo=WeiXinCacheUtil.getInfo();
        EventBus.getDefault().register(this);
        init();
        loadingView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(wxInfo.isLogin()){
                    loadGroup();
                }else {
                    WeiXinLoginActivity.openWeiXingLoginUI(getApplicationContext());
                }

            }
        });
        loadGroup();
    }

    private void  loadGroup(){
        if(!wxInfo.isLogin()){
            loadingView.showError("微信未登录,请先登录");
            return;
        }
        XHttp.obtain().get(WGJAPI.getWeiXinGroupByAll(CacheUtils.getMember().getM_id(),wxInfo.getWxuin()),null,new ListHttpCallBack<Group>(){


            @Override
            public void onSuccess(List<Group> list) {
                  if(list==null || list.size()==0){
                      loadingView.showEmpty("暂无分组");
                  }else {
                      groupAdapter.notifyDataSetChanged(list);
                      loadingView.showContent();
                  }
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                if(b){
                    loadingView.showNoNetwork();
                }else {
                    loadingView.showError();
                }
            }
        });

    }

    private  void init(){
         groupAdapter=new GroupAdapter(this,groups);
         topbarView.setTopBarClickListener(new XTopbarView.OnTopBarClickListener() {
             @Override
             public void onBackClick() {
                 finish();
             }

             @Override
             public void onRightButClick() {
                 if(TextUtils.isEmpty(wxInfo.getWxuin())){
                     XToast.error("请先登录微信");
                     return;
                 }

                 new ModifyGroupDialog().setGroupListener(new ModifyGroupDialog.OnGroupListener() {
                     @Override
                     public void addGroup(String groupName) {
                         XLoadingDialog.with(WXGroupActivity.this).setMessage("正在提交中..").show();
                         Map<String,Object> params=new HashMap<>();
                         params.put("groupname",groupName);
                         params.put("uuid",WeiXinCacheUtil.getInfo().getWxuin());
                         params.put("mId",CacheUtils.getMember().getM_id());
                         XHttp.obtain().post(WGJAPI.BASEURL.concat("wxgroup/save"), params, new HttpCallBack<String>() {
                             @Override
                             public void onSuccess(String s) {
                                  XToast.success("添加成功");
                                  XLoadingDialog.with(WXGroupActivity.this).dismiss();
                                  loadGroup();
                             }
                            @Override
                             public void onFailed(int i, String s, boolean b) {
                                 XToast.success("添加失败");
                                 XLoadingDialog.with(WXGroupActivity.this).dismiss();
                             }
                         });
                     }
                 }) .show(getSupportFragmentManager(),"ModifyGroupDialog");
             }
         });
         groupListView.setLayoutManager(new LinearLayoutManager(this));
         groupListView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(this,R.color.divider)));
         groupListView.setSwipeItemClickListener(new SwipeItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }
        });
        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {
                SwipeMenuItem synchroItem = new SwipeMenuItem(WXGroupActivity.this);
                synchroItem.setBackground(R.color.synchro_menu_bg);
                synchroItem.setText("同步");
                synchroItem.setTextSize(10);
                synchroItem.setTextColor(Color.WHITE);
                synchroItem.setWidth(XDensityUtils.dp2px(80));
                synchroItem.setHeight(MATCH_PARENT);
                rightMenu.addMenuItem(synchroItem);
                SwipeMenuItem delItem = new SwipeMenuItem(WXGroupActivity.this);
                delItem.setBackground(R.color.del_menu_bg);
                delItem.setText("删除");
                delItem.setTextSize(10);
                delItem.setTextColor(Color.WHITE);
                delItem.setWidth(XDensityUtils.dp2px(80));
                delItem.setHeight(MATCH_PARENT);
                rightMenu.addMenuItem(delItem);

            }
        };
        groupListView.setSwipeMenuCreator(mSwipeMenuCreator);
        groupListView.setSwipeMenuItemClickListener(new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                menuBridge.closeMenu();//关闭菜单
            }
        });
        groupListView.setAdapter(groupAdapter);
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetFirendsEvent(ContactEvent event){
        XLoadingDialog.with(this).dismiss();
       loadGroup();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public  void onWeiXinLogin(WeiXinEvents events){
        if(events.getType()==WeiXinEvents.EventsType.LOGIN){
            wxInfo=WeiXinCacheUtil.getInfo();
            XLoadingDialog.with(this).setMessage("正在获取微好友信息,请稍等").show();
            Intent intent=new Intent(getApplication(), GetWXFriendService.class);
            startService(intent);
        }else if(events.getType()==WeiXinEvents.EventsType.LOGIN_OUT){
            wxInfo=new WXInfo();
        }
    }
}
